package com.wanxi.tcp.demo4客户端发送文件给服务器;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

/**
 * TCP服务器端，服务器端接收客户端上传的文件
 */
public class TCPServer {
    public static void main(String[] args) throws IOException {
        System.out.println("tcp 服务端启动.....");
        //1. 创建服务器端socket
        ServerSocket serverSocket = new ServerSocket(30000);

        System.out.println("等待客户端的连接....");
        while (true) {
            //2 建立客户端socket通道,阻塞形式
            Socket socket = serverSocket.accept();
            System.out.println("客户端上传文件了.....");
            //3 创建输入流 建立soket通道,阻塞形式
            InputStreamReader reader = new InputStreamReader(socket.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(reader);
            //4 接收上传的信息
            String content = "";
            // 创建本地文件输出流
//
//            String fileName = UUID.randomUUID().toString();
            String fileName = System.currentTimeMillis() + "";
            //写到本地文件，所以嵌套的是一个文件流FileWriter
            String path = "E:\\wanxi\\step-2\\java02-0921\\day22网络编程基础\\src\\com\\wanxi\\tcp\\demo4客户端发送文件给服务器";
            BufferedWriter fileWriter = new BufferedWriter(new FileWriter(path + "/" + fileName + ".txt"));
            System.out.println("读取客户端文件内容开始保存.....");
            while ((content = bufferedReader.readLine()) != null) {
                fileWriter.write(content + "\r\n");
//                fileWriter.newLine();
                fileWriter.flush();
            }
            fileWriter.close();
            System.out.println("客户端文件保存完毕，文件路径为：" + "file/" + fileName + ".js");
        }
    }
}
